package com.pj.xfxh.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pj.project.sys_client.SysClient;
import com.pj.project.sys_client.SysClientMapper;
import com.pj.utils.sg.AjaxJson;
import com.pj.xfxh.project.entity.Topic;
import com.pj.xfxh.project.entity.TopicMessage;
import com.pj.xfxh.project.service.TopicMessageService;
import com.pj.xfxh.project.service.TopicService;
import com.pj.xfxh.service.XhService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@SaIgnore
@RestController
@RequestMapping("/xh")
@Slf4j
public class XhController {

    @Resource
    private XhService service;
    @Autowired
    private TopicService topicService;
    @Autowired
    private TopicMessageService topicMessageService;
    /** 底层 Mapper 对象 */
    @Autowired
    public SysClientMapper sysClientMapper;

    @GetMapping("/ask")
    public AjaxJson ask(@RequestParam("question") String question,
                        @RequestParam("userId") Long userId,
                        @RequestParam(value = "topicId", required = false) Long topicId,
                        @RequestParam("platformId") Long platformId) throws Exception {

        // 检查平台是否录入
        SysClient sysClient = sysClientMapper.getById(platformId);
        if (sysClient == null) {
            return AjaxJson.getError("平台未录入！");
        }

        // 获取或创建话题
        AjaxJson topicResult = getOrCreateTopic(topicId,userId, platformId, question);
        if (topicResult.getCode()==AjaxJson.CODE_ERROR) {
            return topicResult; // 返回错误信息给前端
        }

        // 如果成功创建了话题，则将topicId设置为新消息的话题id
        Topic existingTopic = (Topic) topicResult.getData();
        if(existingTopic != null) topicId=existingTopic.getTopicId();
        List<TopicMessage> topicMessageList = service.ask(question, userId, topicId, platformId);

        //最终只返回AI的回答的内容
        TopicMessage first = topicMessageList.stream()
                .filter(topicMessage -> "assistant".equals(topicMessage.getDialogueRole()))
                .findFirst()
                .get();

        return AjaxJson.getSuccessData(first);
    }

    /**
     * 获取或创建话题
     */
    private AjaxJson getOrCreateTopic(Long topicId, Long userId, Long platformId, String question) {
        QueryWrapper<Topic> queryWrapper = Wrappers.query();
        queryWrapper.lambda()
                .eq(Topic::getTopicId, topicId);

        // 查找已存在的话题
        Topic existingTopic = topicService.getOne(queryWrapper);

        if (existingTopic != null) {
            return AjaxJson.getSuccess(); // 返回已存在的话题
        }

        return createTopic(userId, platformId, question);
    }

    /**
     * 创建新话题
     */
    private AjaxJson createTopic(Long userId, Long platformId, String question) {
        // 检查用户话题数量是否超过限制
        long topicCount = topicService.count(Wrappers.lambdaQuery(Topic.class)
                .eq(Topic::getUserId, userId)
                .eq(Topic::getPlatformId, platformId));

        if (topicCount >= 10) {
            return AjaxJson.getError("您已超过十个话题");
        }

        // 创建新话题
        Topic newTopic = new Topic();
        newTopic.setTopicName(question);
        newTopic.setPlatformId(platformId);
        newTopic.setUserId(userId);
        topicService.save(newTopic);
        return AjaxJson.getSuccessData(newTopic); // 返回新创建的话题
    }

}
